package com.demo.springboot.controller;

import com.alibaba.fastjson.JSONObject;

import com.demo.springboot.entity.CorrectJsonObject;
import com.demo.springboot.entity.ErrorJsonObject;
import com.demo.springboot.entity.News;
import com.demo.springboot.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping(value = "/news")
public class NewsController {

    @Autowired
    NewsService newsService;

    @GetMapping(value = "/getNews")
    public String  getNewsById(@RequestParam(value = "id",required = false) Integer id) {

        News news = newsService.findById(id);

        if(news != null) {
            CorrectJsonObject correctJsonObject = new CorrectJsonObject("查询成功");
            correctJsonObject.setData(news);
            return JSONObject.toJSONString(correctJsonObject);
        }else {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(100,"查询失败");
            return JSONObject.toJSONString(errorJsonObject);
        }
    }

    @PostMapping(value = "/addNews")
    public String addRecord(@RequestParam(required = false) News news) {

        if(news == null) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(101,"参数为空");
            return JSONObject.toJSONString(errorJsonObject);
        }

        int result = newsService.insertARecord(news);

        if(result != 1) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(102,"插入失败");
            return JSONObject.toJSONString(errorJsonObject);
        }else {
            CorrectJsonObject correctJsonObject = new CorrectJsonObject("插入成功");
            return JSONObject.toJSONString(correctJsonObject);
        }
    }
}
